package no.evalanche.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.cookie.BasicClientCookie2;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.http.AndroidHttpClient;
import android.os.Handler;
import android.util.Log;

public class Authenticator extends MC_Async {

	

	public Authenticator(Handler h) {
		handler = h;
	}

	@Override
	protected JSONObject doInBackground(EntityList ... pams) {
		JSONObject jsonObject = null;
		AndroidHttpClient httpclient = AndroidHttpClient.newInstance("android");
		HttpPost request = new HttpPost(ServiceList.URL.toString());
		try {
			request.setEntity(new UrlEncodedFormEntity(pams[0]));		
			HttpResponse r = httpclient.execute(request);
			jsonObject = jsonFromEntity(r);			
			jsonObject.put("sessionid", sessionIdFromHeader(r)); 
			httpclient.close();
		} catch (IOException e) {
			Log.d("EvalancheAuthenticator",e.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	private String sessionIdFromHeader(HttpResponse r) {
		// Assuming only *one* Set-Cookie
		Header cc = r.getHeaders("set-Cookie")[0];
		String[] a = cc.getValue().split("="); // getValue is a "key=value"
		BasicClientCookie2 c = new BasicClientCookie2(a[0], a[1]);		
		return c.getValue();
	}

	private JSONObject jsonFromEntity(HttpResponse r) throws IOException {
		HttpEntity httpEntity = r.getEntity();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				httpEntity.getContent()));
		String line;
		StringBuilder builder = new StringBuilder();
		while ((line = br.readLine()) != null) {
			builder.append(line);
		}
		try {
			return new JSONObject(builder.toString());
		} catch (JSONException e) {
			return new JSONObject();
		}
	}

}
